package com.example.module_publish


import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.tencent.live2.V2TXLiveCode.V2TXLIVE_ERROR_INVALID_LICENSE
import com.tencent.live2.V2TXLiveDef
import com.tencent.live2.V2TXLivePusher
import com.tencent.live2.impl.V2TXLivePusherImpl
import com.tencent.rtmp.ui.TXCloudVideoView


@Route(path = "/module_publish/PublishActivity")
class PublishActivity : AppCompatActivity() {
    private lateinit var  mLivePusher:V2TXLivePusher
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_publish)
        //动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(arrayOf(
                "android.permission.ACCESS_NETWORK_STATE",
                "android.permission.ACCESS_WIFI_STATE",
                "android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.RECORD_AUDIO",
                "android.permission.MODIFY_AUDIO_SETTINGS",
                "android.permission.BLUETOOTH",
                "android.permission.CAMERA",
                "android.permission.READ_PHONE_STATE",
            ),101)
        }


        // 指定对应的直播协议为 RTMP，该协议不支持连麦
        mLivePusher = V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP)

        // 启动本地摄像头预览
        val mPusherView = findViewById<TXCloudVideoView>(R.id.pusher_tx_cloud_view)
        mLivePusher.setRenderView(mPusherView)
        mLivePusher.startCamera(true)
        mLivePusher.startMicrophone()



    }

    fun startPush(view: View) {
        //1:访问创建直播间接口返回推流地址：此处自己完成
        //2:开始推流
        // 根据推流协议传入对应的 URL 即可启动推流， RTMP 协议以 rtmp:// 开头，该协议不支持连麦
        val url = "rtmp://3891.livepush.myqcloud.com/live/3891_user_970f5c16_ff3b?bizid=3891&txSecret=5412fda190fdb5d26a6b1bd11cca101b&txTime=67C7F1A1"
        val ret: Int = mLivePusher.startPush(url)
        if (ret == V2TXLIVE_ERROR_INVALID_LICENSE) {
            Log.i("TAG", "startRTMPPush: license 校验失败")
        }else{
            Log.i("TAG", "推流成功")
        }
    }

    fun endPush(view: View) {
        //1:访问删除直播间接口
        //2:停止推流
        mLivePusher.stopPush()
    }
}